/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmConexion.java
 *
 * Created on 28-jun-2011, 2:57:53
 */
package verins.GUI;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import verins.Utils.Comunes;
import verins.Utils.IOmethods;
import verins.Utils.Mensajes;

/**
 *
 * @author hectdx
 */
public class frmConexion extends javax.swing.JFrame {

    /** Creates new form frmConexion */
    List<String> conexiones=new ArrayList<String>();
    String conexActual="";
    public frmConexion() {
        initComponents();
        Comunes.centrarVentana(this);
        setValidadores();
        conexiones.add("jdbc:postgresql://127.0.0.1:5432/veri,postgres,contra");
        conexiones.add("jdbc:postgresql://quilla.lab.inf.pucp.edu.pe:1042/postgres,postgres,victoria");
        Comunes.llenarCombo(cmbConex, conexiones);
        conexiones=leerConexion();
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmbConex = new javax.swing.JComboBox();
        jpNueva = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtServ = new javax.swing.JTextField();
        txtPuerto = new javax.swing.JTextField();
        txtBD = new javax.swing.JTextField();
        txtuser = new javax.swing.JTextField();
        pass = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Conexiones a bd");
        setResizable(false);

        cmbConex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbConexActionPerformed(evt);
            }
        });

        jpNueva.setBorder(javax.swing.BorderFactory.createTitledBorder("Nueva conexión"));

        jLabel2.setText("Servidor");

        jLabel3.setText("Puerto");

        jLabel4.setText("BD");

        jLabel5.setText("Usuario");

        jLabel6.setText("Contraseña");

        javax.swing.GroupLayout jpNuevaLayout = new javax.swing.GroupLayout(jpNueva);
        jpNueva.setLayout(jpNuevaLayout);
        jpNuevaLayout.setHorizontalGroup(
            jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpNuevaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpNuevaLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jpNuevaLayout.createSequentialGroup()
                                .addComponent(txtBD, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6))
                            .addGroup(jpNuevaLayout.createSequentialGroup()
                                .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE)
                                .addComponent(jLabel5)))
                        .addGap(58, 58, 58)
                        .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pass)
                            .addComponent(txtuser, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpNuevaLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtServ, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jpNuevaLayout.setVerticalGroup(
            jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpNuevaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtServ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5)
                    .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtuser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jpNuevaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6)
                    .addComponent(txtBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        jLabel1.setText("Conexiones registradas");

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmbConex, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jpNueva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbConex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jpNueva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnAceptar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

     private void setValidadores(){
        txtPuerto.setDocument(new verins.Utils.LimitInput(5));
        txtPuerto.addKeyListener(verins.Utils.Verificador.verificaSoloNumeros());
       
    }
    private void mostrarConexion(String strConex){
       System.out.println(strConex);
        String [] strData=null;
                
         strData=strConex.split(",");
         if(strData!=null){
              String user=strData[1];
              String pass=strData[2]; 
              txtServ.setText(strData[0]);
              txtuser.setText(strData[1]);
              this.pass.setText(strData[2]);
              String serv=strData[0];
              serv=serv.replace("jdbc:postgresql://", "");
              String [] strAux=serv.split(":");
              serv=strAux[0];
              txtServ.setText(serv);
              String []strA=strAux[1].split("/");
              txtPuerto.setText(strA[0]);
              txtBD.setText(strA[1]);
         }else{
            Mensajes.alerta("cadena de conexión errónea");
         }
    }
    
    private List<String> leerConexion(){
        List<String>lstConex=new ArrayList<String>();
        try{
            String fileCon=IOmethods.getRealPath()+"conn";
            String line="";
            BufferedReader reader=new BufferedReader(new FileReader(fileCon));
            while((line=reader.readLine())!=null){
                lstConex.add(line);
            }
            if (!lstConex.isEmpty())
                mostrarConexion(lstConex.get(0));
           reader.close();
            
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        return lstConex;
    }
    
    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
        if (Mensajes.guardar(evt, this)){
            //quilla.lab.inf.pucp.edu.pe:1042/postgres,postgres,victoria
            conexActual="jdbc:postgresql://"+
                        txtServ.getText()+":"+
                    txtPuerto.getText()+"/"+
                    txtBD.getText()+","+
                    txtuser.getText()+","+
                    pass.getText();
           boolean conexOK=IOmethods.guardarConexion(conexActual);
           Mensajes.exito(conexOK);
           if (conexOK)
               dispose();   
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void cmbConexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbConexActionPerformed
        // TODO add your handling code here:
        mostrarConexion(cmbConex.getSelectedItem().toString());
    }//GEN-LAST:event_cmbConexActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmConexion().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbConex;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jpNueva;
    private javax.swing.JPasswordField pass;
    private javax.swing.JTextField txtBD;
    private javax.swing.JTextField txtPuerto;
    private javax.swing.JTextField txtServ;
    private javax.swing.JTextField txtuser;
    // End of variables declaration//GEN-END:variables
}
